import java.util.Stack;

/*
 * @lc app=leetcode.cn id=20 lang=java
 *
 * [20] 有效的括号
 */

// @lc code=start
class Solution {

    /**
     * Accepted
    92/92 cases passed (1 ms)
    Your runtime beats 98.91 % of java submissions
    Your memory usage beats 86.35 % of java submissions (39.3 MB)
     */
    public boolean isValid(String s) {
        if (s == null || s.length() == 0)
            return false;
        int len = s.length();
        // int[] result = new int[3];
        Stack<Character> result = new Stack<Character>();

        try {
            for (int i = 0; i < len; i++) {
                char c = s.charAt(i);
                switch (c) {
                    case '(':
                        result.push(c);
                        break;
                    case ')':
                        char last = result.pop();
                        if (last != '(')
                            return false;
                        break;
                    case '{':
                        result.push(c);
                        break;
                    case '}':
                        char last2 = result.pop();
                        if (last2 != '{')
                            return false;
                        break;
                    case '[':
                        result.push(c);
                        break;
                    case ']':
                        char last3 = result.pop();
                        if (last3 != '[')
                            return false;
                        break;
                    default:
                        return false;
                }
            }
        } catch (Exception e) {
            return false;
        }

        // check final
        if (result.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}
// @lc code=end
